import { DATEFORMAT } from '@/common';
import { getUpDownDay } from '@/utils';
import { Button, DatePicker, Form, message, Table, TimePicker } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { YmDialog } from 'ym-design';

type positionInfoValue = any[];

interface SelDayTimesProps {
  value?: positionInfoValue;
  onChange?: (newVal: positionInfoValue) => void;
}
const requireRules = (text: string) => {
  return [{ required: true, message: text }];
};
const weekList = ['日', '一', '二', '三', '四', '五', '六'];
const dateFormat = 'YYYY-MM-DD';
const timeFormat = 'HH:mm';
const SelDayTimes: React.FC<SelDayTimesProps> = (props) => {
  const { value, onChange } = props;
  const [form] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  let [tableKey, setTableKey] = useState<number>(0);
  const [dayTimesData, setDayTimesData] = useState<any[]>([]);
  // const [seltedData, setSeltedData] = useState<any[]>([]);
  const [startTime, setStartTime] = useState<any[]>([]);
  const [endTime, setEndTime] = useState<any[]>([]);
  const [editIndex, setEditIndex] = useState<number | ''>(''); // 正在编辑的索引，默认为空
  const columns = [
    {
      title: '日期',
      dataIndex: 'studyday',
      key: 'studyday',
      width: 300,
      render: (_: any, record: any) => (
        <div>
          {record.trainTime}(星期{weekList[dayjs(record.trainTime).day()]})
        </div>
      ),
    },
    {
      title: '时间',
      dataIndex: 'studyTime',
      key: 'studyTime',
      width: 400,
      render: (_: any, record: any) => (
        <div>
          {getUpDownDay(record.startTime, 1)}
          {record.startTime}——{getUpDownDay(record.endTime, 1)}
          {record.endTime}
        </div>
      ),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 300,
      render: (_: any, record: any, index: number) => (
        <div>
          <Button
            type="text"
            onClick={() => {
              setEditIndex(index);
              form.setFieldValue('selData', dayjs(record.trainTime, dateFormat));
              setStartTime(record.startTime);
              setEndTime(record.endTime);
              form.setFieldValue('selTime', [dayjs(record.startTime, timeFormat), dayjs(record.endTime, timeFormat)]);
              setIsModalOpen(true);
            }}
          >
            <a>编辑</a>
          </Button>
          <Button
            type="text"
            onClick={() => {
              const list = dayTimesData;
              list.splice(index, 1);
              setDayTimesData(list.slice());
              onChange?.(dayTimesData);
            }}
          >
            <a>删除</a>
          </Button>
        </div>
      ),
    },
  ];
  useEffect(() => {
    setDayTimesData(value || []);
  }, [value]);
  const handleOk = () => {
    form.validateFields().then((values) => {
      console.log(values.selData.format(DATEFORMAT), '打印看看周期arr');
      const list = dayTimesData;
      if (startTime == endTime) return message.error('开始结束时间不能相等');
      if (editIndex === '')
        list.push({ trainTime: values.selData.format(DATEFORMAT), startTime: startTime, endTime: endTime });
      else
        list[editIndex] = Object.assign(
          {},
          { trainTime: values.selData.format(DATEFORMAT), startTime: startTime, endTime: endTime },
        );

      setDayTimesData(list.slice());
      setTableKey(++tableKey);
      setIsModalOpen(false);
      onChange?.(dayTimesData);
    });
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <div>
      <Button
        onClick={() => {
          setEditIndex('');
          setIsModalOpen(true);
          form.resetFields();
        }}
        style={{ marginBottom: 15 }}
      >
        添加培训日期
      </Button>
      {dayTimesData.length > 0 && (
        <Table key={tableKey} columns={columns} dataSource={dayTimesData} pagination={false} />
      )}
      <YmDialog
        title="培训日期"
        centered
        width={480}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        onClose={handleCancel}
        destroyOnClose={true}
      >
        <Form layout="horizontal" labelAlign="right" form={form}>
          <Form.Item label="选择日期" name="selData" rules={requireRules('请选择日期')}>
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="选择时间" name="selTime" rules={requireRules('请选择时间')} style={{ marginBottom: 0 }}>
            <TimePicker.RangePicker
              style={{ width: '100%' }}
              onChange={(time1: any, time2: any) => {
                setStartTime(time2[0]);
                setEndTime(time2[1]);
              }}
              format={'HH:mm'}
            />
          </Form.Item>
        </Form>
      </YmDialog>
    </div>
  );
};
export default SelDayTimes;
